import React, { useState, useEffect, useCallback, useReducer } from 'react';
import { Modal, Card, Form, message, Input, Popconfirm, Select, InputNumber, Button } from 'antd';
import { ILiftControl, batchAddLiftControls, deleteLiftControlApi, LiftingControlType } from 'api/LiftControl';
import { useRequest, useToggle } from 'ahooks';
import { FormInstance } from 'antd/lib/form';
import { IArea } from 'api/Area';
import { MinusCircleOutlined } from '@ant-design/icons';
import { checkIpAddressList } from 'api/OnlineLiftingControl';
interface IEditModalProps {
    visible: boolean;
    toggleVisible: (value: boolean) => void;
    areas: IArea[];
    isEdit: boolean;
    editLiftControls: ILiftControl[];
    refresh: Function
}
interface ILiftControlEdit {
    id: number;
    form: FormInstance | undefined;
    originData?: ILiftControl;
    isOnline: boolean | string;
}
interface ILiftControlProps {
    areas: IArea[];
    liftControl: ILiftControlEdit;
    updateLiftControl: any;
    toggleIsAllChecked: (value: boolean) => void;
}
let formList: any = [];
const LiftControl = (props: ILiftControlProps) => {
    const [confirmVisible, { toggle: toggleConfirmVisible }] = useToggle(false);
    const { run: deleteLiftControlRun } = useRequest(deleteLiftControlApi, {
        manual: true,
    });
    const [form, dispatch] = useReducer(reducer, Form.useForm()[0])
    function reducer(state: any, action: any) {
        if (action.type === 'init') {
            if (props.liftControl.originData) {
                state.setFieldsValue(props.liftControl.originData);
                formList.push(state);
            } else {
                setTimeout(() => {
                    props.updateLiftControl({ ...props.liftControl, form: state });
                })
            }
            return state
        }
    }
    useEffect(() => {
        dispatch({ type: 'init' })
    }, [dispatch]);
    /** 点击减号图标 */
    const handleVisibleChange = () => {
        if (props.liftControl.originData) {
            // 已存在摄像机
            toggleConfirmVisible(true);
        } else {
            // 新增加的摄像机
            props.updateLiftControl(props.liftControl, 'delete');
        }
    };
    const confirmDelete = async () => {
        await deleteLiftControlRun([props.liftControl.id]);
        message.success('删除控制箱成功');
        props.updateLiftControl(props.liftControl, 'delete');
    };
    const cancel = () => {
        toggleConfirmVisible(false);
    };
    return (
        <Card className="mb10 control-item" hoverable>
            <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                <Form.Item label="IP地址">
                    <Form.Item
                        name="ipAddress"
                        rules={[
                            { required: true, message: '请输入IP地址' },
                            () => ({
                                validator() {
                                    if (props.liftControl.isOnline === 'error') {
                                        return Promise.reject('请输入正确的IP!');
                                    }
                                    return Promise.resolve();
                                },
                            }),
                        ]}
                        validateFirst
                        noStyle
                    >
                        <Input
                            placeholder="请输入IP地址"
                            style={{ width: 270, marginRight: 10 }}
                            onChange={() => props.toggleIsAllChecked(false)}
                            disabled={Boolean(props.liftControl.originData)}
                            allowClear
                        />
                    </Form.Item>
                    <Popconfirm
                        title="确定删除该设备?"
                        visible={confirmVisible}
                        onVisibleChange={handleVisibleChange}
                        onConfirm={confirmDelete}
                        onCancel={cancel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <MinusCircleOutlined className="font-20" />
                    </Popconfirm>
                </Form.Item>
                <Form.Item label="设备区域" name="areaId" rules={[{ required: true, message: '请选择设备区域' }]}>
                    <Select allowClear>
                        {props.areas.map((area) => (
                            <Select.Option key={area.id} value={area.id || -1}>
                                {area.name}
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                {props.liftControl.isOnline === true && (
                    <>
                        <Form.Item label="路桩型号" name="type">
                            <Select disabled>
                                <Select.Option value={0}>{LiftingControlType[0]}</Select.Option>
                                <Select.Option value={1}>{LiftingControlType[1]}</Select.Option>
                                <Select.Option value={2}>{LiftingControlType[2]}</Select.Option>
                            </Select>
                        </Form.Item>
                        <Form.Item label="在线路桩数" name="onlineNum">
                            <Input disabled />
                        </Form.Item>
                    </>
                )}
            </Form>
        </Card>
    );
};

const LiftControlEdit = (props: IEditModalProps) => {
    const [liftControlList, setLiftControlList] = useState<ILiftControlEdit[]>([]);
    const [isEdit, setIsEdit] = useState(false);
    const [isAllChecked, toggleIsAllChecked] = useState(false);
    const { run: saveBatchLiftControlRun, loading: saveBatchLiftControlLoading } = useRequest(batchAddLiftControls, {
        manual: true,
    });
    useEffect(() => {
        if (!props.visible) {
            // 关闭弹框清除数据
            setLiftControlList([]);
            return;
        }
        console.log('modalInit', props.editLiftControls);
        formList = [];
        let timer: any;
        if (props.visible) {
            if (props.isEdit) {
                const editLiftControlList = props.editLiftControls.map((liftControl) => ({
                    id: liftControl.id,
                    form: undefined,
                    originData: liftControl,
                    isOnline: true,
                }));
                toggleIsAllChecked(true)
                setLiftControlList(editLiftControlList);
                timer = setInterval(() => {
                    // 轮询检测form是否更新到CameraEdit
                    console.log(formList.length, editLiftControlList.length);
                    if (formList.length === editLiftControlList.length) {
                        console.log('formList', formList);
                        const result = editLiftControlList.map((liftControl, index) => {
                            liftControl.form = formList[index];
                            return liftControl;
                        });
                        setLiftControlList(result);
                        clearInterval(timer);
                    }
                });
            } else {
                setLiftControlList([
                    {
                        id: Math.random(),
                        form: undefined,
                        isOnline: false,
                    },
                ]);
            }
        }
        setIsEdit(props.isEdit);
        return () => {
            clearInterval(timer);
        };
    }, [props.visible]);
    /** 搜索、确定 */
    const okClick = async () => {
        if (!isAllChecked) {
            // ip地址不是都Ok的 检查所有ipAddress
            const ipAddressList = liftControlList
                .map((liftControl) => liftControl.form?.getFieldValue('ipAddress'))
                .join(',');
            if (ipAddressList === '') return;
            const ipCheckResult = await checkIpAddressList({ ipAddressList });
            console.log('ipCheckResult', ipCheckResult);
            const newLiftControlList = liftControlList.map((liftControl) => {
                if (liftControl.originData) {
                    return liftControl
                }
                const ipAddress = liftControl.form?.getFieldValue('ipAddress');
                const isOnline = Boolean(ipCheckResult[ipAddress]) ? true : 'error';
                liftControl.isOnline = isOnline;
                if (isOnline) {
                    liftControl.form?.setFieldsValue({
                        onlineNum: ipCheckResult[ipAddress]?.onlineNum,
                        type: ipCheckResult[ipAddress]?.type,
                    });
                }
                return liftControl;
            });
            toggleIsAllChecked(newLiftControlList.every((liftControl) => liftControl.isOnline === true));
            newLiftControlList.forEach((liftControl) => {
                liftControl.form?.validateFields(['ipAddress']);
            });
            console.log('newLiftControlList', newLiftControlList);
            setLiftControlList(newLiftControlList);
            return;
        }
        let validates: any = [];
        liftControlList.map((liftControl) => validates.push(liftControl.form?.validateFields()));
        await Promise.all(validates); // 校验全部摄像头表单
        const result = liftControlList.map((liftControl) => {
            if (liftControl.originData) {
                return {
                    id: liftControl.id,
                    ...liftControl.form?.getFieldsValue(),
                };
            }
            return { ...liftControl.form?.getFieldsValue() };
        });
        console.log(result);
        saveBatchLiftControlRun(result).then(() => {
            message.success('修改成功');
            props.toggleVisible(false);
            props.refresh()
        });
    };
    /** 关闭弹框 */
    const cancelClick = () => {
        props.toggleVisible(false);
        props.refresh()
    };
    /** 添加摄像头 */
    const addLiftControl = () => {
        console.log('addLiftControl')
        setLiftControlList([...liftControlList, { id: Math.random(), form: undefined, isOnline: false }]);
        toggleIsAllChecked(false)
        setTimeout(() => {
            const doms = document.getElementsByClassName('control-item')
            if (doms.length === 0) return
            doms[doms.length -1].scrollIntoView()
        })
    }
    /** 更新单个摄像头 */
    const updateLiftControl = useCallback((newLiftControl: any, type: string) => {
        if (type === 'delete') {
            setLiftControlList(liftControlList.filter((liftControl) => liftControl.id !== newLiftControl.id));
            return;
        }
        const result = liftControlList.map((liftControl) => {
            return liftControl.id === newLiftControl.id ? newLiftControl : liftControl;
        });
        setLiftControlList(result);
    }, [liftControlList])
    return (
        <Modal
            visible={props.visible}
            title={isEdit ? '设备编辑' : '设备添加'}
            okText={isAllChecked ? '确定' : '搜索'}
            cancelText="取消"
            onOk={okClick}
            onCancel={cancelClick}
            bodyStyle={{ padding: '10px 10px 0 10px' }}
            destroyOnClose
            okButtonProps={{ disabled: liftControlList.length === 0 || saveBatchLiftControlLoading }}
        >
            <div className="text-right mb10 pb10" style={{ borderBottom: '1px solid #ccc' }}>
                <Button type="primary" onClick={addLiftControl}>添加</Button>
            </div>
            <div className="control-list">
                {liftControlList.map((liftControl) => (
                    <LiftControl
                        key={liftControl.id}
                        areas={props.areas}
                        updateLiftControl={updateLiftControl}
                        liftControl={liftControl}
                        toggleIsAllChecked={toggleIsAllChecked}
                    />
                ))}
            </div>
        </Modal>
    );
};
export default LiftControlEdit;
